package scheduler

import "webProject/crawler"

//定义行为
type Scheduler interface {
	Submit(crawler.Request)
	Run()
	// 返回一个传输数据给worker的通道
	WorkerChan() chan crawler.Request
	WorkerReady(chan crawler.Request)
}

//队列版的调度器
type QueueScheduler struct {
	requestChan chan crawler.Request
	workerChan chan chan crawler.Request
}

func (q *QueueScheduler) WorkerReady(w chan crawler.Request) {
	//当worker就绪了可以进行下一个处理的时候，将其加入到workChan里去
	q.workerChan <- w
}

func (q *QueueScheduler) Submit(sub crawler.Request) {
	q.requestChan <- sub
}

func (q *QueueScheduler) Run() {
	//先初始化两个chan
	q.requestChan = make(chan crawler.Request)
	q.workerChan = make(chan chan crawler.Request)
	go func() {
		var requestQ []crawler.Request
		var workerQ []chan crawler.Request

		for{
			var activeWorker chan crawler.Request
			var activeRequest crawler.Request
			if len(requestQ)>0 && len(workerQ)>0{
				//取出任务和worker
				activeRequest = requestQ[0]
				activeWorker = workerQ[0]
			}
			select {
			case r := <- q.requestChan:
				//取到任务了，加进队列去
				requestQ = append(requestQ, r)
			case w := <- q.workerChan:
				//取到工人了，加到工人队列去
				workerQ = append(workerQ,w)
			case activeWorker <- activeRequest:
				workerQ = workerQ[1:]
				requestQ = requestQ[1:]
			}
		}
	}()
}

func (q *QueueScheduler) WorkerChan() chan crawler.Request {
	return make(chan crawler.Request)
}